import os

path = '主要业务'  # 文件所在文件夹
# 获取相应下的文件名,并拼接完整路径
files = [path + "\\" + i for i in os.listdir(path)]
import jieba
import wordcloud
from pandas import DataFrame  # 将得到的数据进行表格化

a = 0  # 用作后面给词云图起名
# 设置循环一次处理6个文件
for file in files:

    txt = open(file, "r", encoding="utf-8").read()
    words = jieba.lcut(txt)
    wordsDict = {}  # 新建字典用于储存词及词频
    for word in words:
        if len(word) == 1:  # 单个的字符不作为词放入字典
            continue
        else:
            wordsDict[word] = wordsDict.get(word, 0) + 1
    # 设置图片大小和字体
    w = wordcloud.WordCloud(width=1000, font_path='C:/Windows/Fonts/simhei.ttf', height=800)
    w.generate("".join(words))
    a += 1
    w.to_file('computerlanguage' + str(a) + ".png")
    # 按字典的值降序排序
    wordsDict_seq = sorted(wordsDict.items(), key=lambda x: x[1], reverse=True)
    new_dict = {}
    for i in range(15):
        word, count = wordsDict_seq[i]
        print(f"{word}:{count}")
        new_dict[word] = count
    print('-' * 20)
    # 将前十五的数据表格化并加入行标（"词"，"次数"）和列标（默认0-14）
    df = DataFrame(new_dict.items(), columns=['词', '次数'])
    # 将处理后的数据存入Excel中并将所得文件保存在"词频"文件夹里下。
    df.to_excel("词频//{}.xlsx".format(file.split("\\")[1][:-4]))
